package com.example.wechar.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.wechar.pojo.AccessTokenBean;
import com.example.wechar.service.UserInfoService;
import com.example.wechar.utils.HttpClientUtil;
import com.example.wechar.utils.WxCharConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Value("${wx.appId}")
    private String addId;
    @Value("${wx.secret}")
    private String secret;

    private AccessTokenBean accessTokenBean;

    @Override
    public AccessTokenBean getAccesstoken() {
        try{
            synchronized ("lock"){
                if(accessTokenBean==null || accessTokenBean.isExpired()){
                    refreshAccessToken(addId,secret);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("----------刷新Access_token时出现异常,释放锁");
        }

        return accessTokenBean;
    }

    private void refreshAccessToken(String appId, String appSecret) {
        String s = HttpClientUtil.doGet(WxCharConstant.ACCESS_TOKEN_URL.replaceAll("APPID", addId).replaceAll("APPSECRET", secret));
        JSONObject jsonObject = JSONObject.parseObject(s);
        long expires_in = jsonObject.getLong("expires_in");
        String access_token = jsonObject.getString("access_token");
        accessTokenBean = AccessTokenBean.responseOf(access_token, expires_in);
        System.out.println(accessTokenBean);
    }

}

